package com.hongkuncheng.cms.controller.admin;

import java.io.File;
import java.util.List;
import java.util.ArrayList;

import org.hibernate.Criteria;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.CookieHelper;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.FileHelper;
import com.hongkuncheng.cms.helper.HttpHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.StringHelper;
import com.hongkuncheng.cms.helper.WeiboHelper;
import com.hongkuncheng.cms.model.Admin;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.Zhuanti;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 微博平台
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/weibo")
public class AweiboController extends BaseController {

    private Criteria getArticleCriteria(List<Criterion> criterions) {
        Criteria criteria = factorySession.createCriteria(Article.class, "this_")
                .createAlias("articleReColumnses", "arc", JoinType.LEFT_OUTER_JOIN)
                .createAlias("arc.columns", "article_columns", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_columns.zhuanti", "article_columns_zhuanti", JoinType.LEFT_OUTER_JOIN)
                .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.department", "article_admin_department", JoinType.LEFT_OUTER_JOIN)
                .createAlias("article_admin.adminGlobalpermission",
                        "article_admin_adminGlobalpermission", JoinType.LEFT_OUTER_JOIN);
        for (Criterion criterion : criterions) criteria.add(criterion);
        return criteria;
    }

    // 微博同步
    @RequestMapping("sync")
    public String sync() throws Exception {
        if (request.getSession().getAttribute("weiboAccessToken") == null) {
            if (WeiboHelper.appKey != null && WeiboHelper.appSecret != null)
                response.sendRedirect("https://api.weibo.com/oauth2/authorize?client_id=" + WeiboHelper.appKey +
                        "&redirect_uri=" + HttpHelper.getHost(request) + WeiboHelper.callbackUrl + "&response_type=code");
            else
                PageHelper.alertAndGoBack("您还未对新浪微博进行授权设置");
            return null;
        } else {
            Admin admin = (Admin) request.getSession().getAttribute("admin");
            List<Criterion> criterions = new ArrayList<Criterion>();
            StringBuilder callbackparams = new StringBuilder();
            criterions.add(Restrictions.isNotNull("digest"));
            boolean onlyme = request.getParameter("onlyme") != null;
            request.setAttribute("onlyme", onlyme);
            if (onlyme || admin.getAdminGlobalpermission().getId() == 1) {
                criterions.add(Restrictions.eq("article_admin.id", admin.getId()));
                callbackparams.append("&onlyme=1");
            } else if (admin.getAdminGlobalpermission().getId() == 2) {
                criterions.add(Restrictions.eq("article_admin_department.id", admin.getDepartment().getId()));
            }
            int columnsId = request.getParameter("columnsid") == null ? -1 :
                    Integer.parseInt(request.getParameter("columnsid"));
            int zhuantiId = request.getParameter("zhuantiid") == null ? -1 :
                    Integer.parseInt(request.getParameter("zhuantiid"));
            if (columnsId > -1) {
                boolean onlycurcolumns = request.getParameter("onlycurcolumns") != null;
                if (onlycurcolumns) {
                    criterions.add(Restrictions.eq("article_columns.id", columnsId));
                    callbackparams.append("&onlycurcolumns=1");
                } else {
                    criterions.add(Restrictions.or(Restrictions.eq("article_columns.id", columnsId),
                            Restrictions.eq("article_columns.parentId", columnsId)));
                }
                request.setAttribute("onlycurcolumns", onlycurcolumns);
                int childCount = Integer.parseInt(factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("parentId", columnsId))
                        .setProjection(Projections.countDistinct("id"))
                        .uniqueResult().toString());
                request.setAttribute("onlycurcolumnsisshow", childCount > 0);
                callbackparams.append("&columnsid=" + columnsId);
            } else if (zhuantiId > -1) {
                criterions.add(Restrictions.eq("article_columns_zhuanti.id", zhuantiId));
                callbackparams.append("&zhuantiid=" + zhuantiId);
            }
            request.setAttribute("columnsid", columnsId);
            request.setAttribute("zhuantiid", zhuantiId);
            String title = request.getParameter("title") == null ? "" : request.getParameter("title");
            if (!title.isEmpty()) {
                criterions.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
                callbackparams.append("&title=" + title);
            }
            request.setAttribute("title", title);
            for (int i = 1; i < 5; i++) {
                Criteria criteArticleState = getArticleCriteria(criterions);
                request.setAttribute("state" + i, criteArticleState
                        .add(Restrictions.eq("articleState.id", i))
                        .setProjection(Projections.count("id"))
                        .setProjection(Projections.countDistinct("id"))
                        .uniqueResult().toString());
            }
            criterions.add(Restrictions.eq("articleState.id", 4));
            Criteria criterTemp = getArticleCriteria(criterions);
            if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
            request.setAttribute("callbackparams", callbackparams);
            int pageIndex = request.getParameter("pageindex") == null ||
                    request.getParameter("callbackparams") != null &&
                            !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                    Integer.parseInt(request.getParameter("pageindex"));
            int datasize = getDataSize();
            List<Integer> articleIds = criterTemp.setProjection(Projections.distinct(Projections.property("id")))
                    .addOrder(Order.desc("id")).setFirstResult((pageIndex - 1) * datasize)
                    .setMaxResults(datasize).list();
            Criteria criteriaArticle = factorySession.createCriteria(Article.class);
            List<Article> articles = new ArrayList<Article>();
            if (articleIds.size() > 0) articles = criteriaArticle.add(Restrictions.in("id", articleIds))
                    .addOrder(Order.desc("id")).list();
            request.setAttribute("articles", articles);
            request.setAttribute("pageindex", pageIndex);
            int recordcount = 0;
            if (articleIds.size() > 0) {
                Criteria criterArticlePage = getArticleCriteria(criterions);
                recordcount = Integer.parseInt(criterArticlePage
                        .setProjection(Projections.countDistinct("id"))
                        .uniqueResult().toString());
            }
            request.setAttribute("recordcount", recordcount);
            int pagecount = DataHelper.calcPageCount(recordcount, datasize);
            request.setAttribute("pagecount", pagecount);
            // 栏目集合
            List<Columns> columnses = new ArrayList<Columns>();
            List<Columns> columnsForZhuanties = new ArrayList<Columns>();
            List<Zhuanti> zhuantis = new ArrayList<Zhuanti>();
            List<Integer> zhuantiIds = new ArrayList<Integer>();
            List<Columns> columns1es = factorySession.createCriteria(Columns.class)
                    .add(Restrictions.eq("parentId", 0))
                    .addOrder(Order.asc("sort")).list();
            for (Columns columns1 : columns1es) {
                List<Columns> columns2Temp = factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("columnsType.id", 1))
                        .add(Restrictions.eq("parentId", columns1.getId()))
                        .addOrder(Order.asc("sort")).list();
                if (columns1.getColumnsType().getId() == 1 || columns2Temp.size() > 0)
                    columnses.add(columns1);
                if (columns2Temp.size() > 0)
                    for (Columns columns2 : columns2Temp) columnses.add(columns2);
                if (columns1.getColumnsType().getId() == 6) {
                    if (!zhuantiIds.contains(columns1.getZhuanti().getId())) {
                        zhuantis.add(columns1.getZhuanti());
                        zhuantiIds.add(columns1.getZhuanti().getId());
                    }
                    columnsForZhuanties.add(columns1);
                }
            }
            request.setAttribute("columnses", columnses);
            request.setAttribute("zhuantis", zhuantis);
            request.setAttribute("columnsForZhuanties", columnsForZhuanties);
            return view();
        }
    }

    // 微博同步处理
    @RequestMapping("syncdo")
    @ResponseBody
    public void syncdo() {
        checkAdminPermission("office_weibo_sync");
        if (CookieHelper.GetCookie(request, "weibo", false) == null) {
            int articleId = Integer.parseInt(request.getParameter("articleid"));
            Article article = factorySession.get(Article.class, articleId);
            String token = request.getSession().getAttribute("weiboAccessToken").toString();
            if (article.getImage() == null || !FileHelper.Exists(applicationDirectory + article.getImage()))
                WeiboHelper.sendText(token, article.getDigest());
            else
                WeiboHelper.sendTextAndImage(token, article.getDigest(), new File(applicationDirectory + article.getImage()));
            CookieHelper.SetCookie(response, "weibo", "1", 300, false);
            PageHelper.alertAndRedirect("文档已成功同步到微博", "sync");
        } else {
            PageHelper.alertAndGoBack("基于微博的防刷机制，\\n您同步的频率太快了，请稍后再试！");
        }
    }

}
